package com.xohm.daemon;

import java.net.*;
import java.util.*;

/**
 * <b>Temporary WebServer Implementation for the Mac since it isn't on the
 * 1.6 JRE version yet.  When they get their act together then we can use
 * the 1.6 HTTP Light Weight Server built into the JRE.</b><br><br>
 */
public class WebServer implements HttpConstants
{
	private static WebServer singleton = null;
	private Thread serverThread = null;
	
	private int port = 9824;
	public Vector<Worker> threads = new Vector<Worker>();
	public int timeout = 5000;
	private int workers = 1;  // 1 threads
	
	private WebServer() {	}
	
	public static WebServer getInstance()
	{
		if (singleton == null)
		{
			singleton = new WebServer();
			singleton.initialize();
		}
		
		return singleton;
	}
	
	public static void main(String[] args)
	{
		WebServer.getInstance();
	}
	
	private void initialize()
	{
		/* start worker threads */
		for (int i = 0; i < workers; ++i)
		{
			Worker worker = new Worker(this);
			(new Thread(worker, "worker #" + i)).start();
			threads.addElement(worker);
		}
		
		serverThread = new Thread(getServer());
		serverThread.start();
		
		System.out.println("Daemon server running on port: "+port+", using "+workers+" threads.");
	}
	
	private Runnable getServer()
	{
		Runnable server = new Runnable()
		{
			public void run()
			{
				try
				{
					ServerSocket serverSocket = new ServerSocket(port);
					while (true)
					{
						// Local App
						Socket socket = serverSocket.accept();
						InetAddress remoteAddr = socket.getInetAddress();
						if (remoteAddr.isLoopbackAddress())
						{
							Worker worker = null;
	
							synchronized (threads)
							{
								if (threads.isEmpty())
								{
									// Can only allow max of 5 connections - No hold queue
									socket.close();
								}
								else
								{
									worker = (Worker)threads.elementAt(0);
									threads.removeElementAt(0);
									worker.setSocket(socket);
								}
							}
						}
						else
						{
							// Remote App - Don't allow access
							socket.close();
						}
					}
				}
				catch (Exception e)
				{
					System.out.println("Daemon WebServer has failed: "+e.toString());
				}
			}
		};
		
		return server;
	}
}